<?php

namespace App\Http\Controllers\Frontend\V10\Common;

use App\Http\Requests\Frontend\V10\Common\uploadRequest;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\File\File;

class FileController extends Controller
{
    public $base_path;
    public function __construct()
    {
        $this->middleware('auth:api');
        $this->base_path = 'frontend/';
    }

    /**
     * Description:上传文件到oss
     * Author: Sam
     * DateTime: 2019/1/15 13:48
     * @param uploadRequest $request
     * @return mixed
     */
    public function upload(uploadRequest $request)
    {
        $type = $request->get('type','img');
        $path = $request->get('path');
        if($type=='img'){
            $file = $request->file('file');
            $file_size = $file->getSize();
            if($file_size > config('common.frontend_max_file_size')){
                return failed('上传图片不能超过2兆');
            }
            $file_path = Storage::disk('oss')->putFile($this->base_path.$path,$file);
            $url = Storage::disk('oss')->url($file_path);
        }else{
            $file = $request->get('file');
            $result = $this->base64ToImg($file);
            $save_file_name = $this->base_path.$path.'/'.md5(time() . 'file' . 'kskd') . '.' . $result['type'];
            $upload = Storage::disk('oss')->put($save_file_name,$result['result']);
            $url = Storage::disk('oss')->url($save_file_name);
            $file_path = str_replace(config('common.oss_endpoint_url'),'',$url);
        }

        return success(['url' => $url,'path' => $file_path]);
    }

    /**
     * Description:base64转换成图片文件
     * Author: Sam
     * DateTime: 2019/1/15 13:49
     * @param $image
     * @return array
     */
    public function base64ToImg($image)
    {
        preg_match('/^(data:\s*image\/(\w+);base64,)/', $image, $result);
        $base64 = base64_decode(str_replace($result[1], '', $image));
        return [
            'type'=>$result[2],
            'result'=>$base64,
        ];
    }
}
